//
//  RegisterInfoViewController.m
//  ChatForHot
//
//  Created by FLY on 2018/10/10.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "RegisterInfoViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "AppDelegate.h"
#import "KeyChain.h"
#import "ProfileHeadView.h"
#import "RegisterCell.h"
#import "SelectView.h"
#import "HOTCHATClipViewController.h"

@interface RegisterInfoViewController ()<CLLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource,SelectDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,ClipViewControllerDelegate>

@property (nonatomic, strong) CLLocationManager* HOTCHATLocation;

@property (nonatomic, strong) NSNumber* HOTCHATlongi;

@property (nonatomic, strong) NSNumber* HOTCHATlati;

@property (nonatomic, strong) ProfileHeadView *HOTCHATheadView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UserInfoModel *model;

@property (nonatomic, strong) SelectView *HOTCHATselectView;

@property (nonatomic, assign) BOOL isSave;

@end

@implementation RegisterInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"StrN013", nil);
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    //Skip
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"StrN014", nil) style:(UIBarButtonItemStylePlain) target:self action:@selector(clickSkip)];
    
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    if (HOTCHATAPPINFO.registerFlag == -2) {
        //first register
        [self HOTCHATbegainLocation];
    }else{
        //again
        [self HOTCHATloginAction];
    }
    
}
- (void)HOTCHATInsertSubViews{
    
    [self.view addSubview:self.HOTCHATbackImgView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.HOTCHATsaveBtn];
    
    [self.HOTCHATbackImgView mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view);
    }];
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.HOTCHATsaveBtn.mas_top).mas_offset(-10);
    }];
    [self.HOTCHATsaveBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(self.view.mas_left).mas_offset(30);
        make.right.mas_equalTo(self.view.mas_right).mas_offset(-30);
        make.bottom.mas_equalTo(self.view.mas_bottom).mas_offset(-40);
    }];
}



//lazzy
- (UIImageView *)HOTCHATbackImgView{
    
    if (_HOTCHATbackImgView == nil) {
        
        _HOTCHATbackImgView = [[UIImageView alloc]init];
        _HOTCHATbackImgView.image = [UIImage imageNamed:@"l_bg"];
        _HOTCHATbackImgView.contentMode = UIViewContentModeScaleAspectFill;
    }
    return _HOTCHATbackImgView;
}
-  (ProfileHeadView *)HOTCHATheadView{
    
    if (_HOTCHATheadView == nil) {
        
        _HOTCHATheadView = [[ProfileHeadView alloc] init];
        _HOTCHATheadView.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 225);
        _HOTCHATheadView.HOTCHATheadImgView.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(HOTCHATclickHeadImgView)];
        [_HOTCHATheadView.HOTCHATheadImgView addGestureRecognizer:tap];
    }
    return _HOTCHATheadView;
}
- (UITableView *)tableView{
    
    if (_tableView == nil) {
        
        _tableView = [[UITableView alloc]init];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [[UIView alloc] init];
        [_tableView registerClass:[ RegisterCell class ] forCellReuseIdentifier:@"RegisterCell"];
        _tableView.tableHeaderView = self.HOTCHATheadView;
        [self.HOTCHATheadView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.top.width.equalTo(self->_tableView);
            make.height.mas_equalTo(225);
        }];
        
    }
    return _tableView;
}
- (UIButton *)HOTCHATsaveBtn{
    
    if (_HOTCHATsaveBtn == nil) {
        
        _HOTCHATsaveBtn = [[UIButton alloc]init];
        [_HOTCHATsaveBtn setBackgroundImage:[[UIImage imageNamed:@"register_save"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 20, 1, 20) resizingMode:(UIImageResizingModeStretch)] forState:UIControlStateNormal];
        [_HOTCHATsaveBtn setBackgroundImage:[[UIImage imageNamed:@"register_save_hig"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 20, 1, 20) resizingMode:(UIImageResizingModeStretch)] forState:UIControlStateHighlighted];
        [_HOTCHATsaveBtn setTitleColor:HOTCHATHexColor(0x8123FF) forState:UIControlStateNormal];
        [_HOTCHATsaveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [_HOTCHATsaveBtn setTitle:NSLocalizedString(@"StrN019", nil) forState:UIControlStateNormal];
        [_HOTCHATsaveBtn addTarget:self action:@selector(HOTCHATsaveAction) forControlEvents:UIControlEventTouchUpInside];
        _HOTCHATsaveBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    }
    return _HOTCHATsaveBtn;
}
- (SelectView *)HOTCHATselectView{
    
    if (_HOTCHATselectView == nil) {
        
        _HOTCHATselectView = [[SelectView alloc] init];
        _HOTCHATselectView.delegate = self;
    }
    return _HOTCHATselectView;
}

- (void)HOTCHATclickHeadImgView{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *manAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"StrN027", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self HOTCHATopenCamera];
    }];
    UIAlertAction *womenAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"StrN028", nil) style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self HOTCHATopenPhoto];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"StrN025", nil) style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [alert addAction:manAction];
    [alert addAction:womenAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 拍照、相册
- (void)HOTCHATopenCamera{
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
    }else{
        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    }
    [imagePicker setDelegate:self];
    
    [self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)HOTCHATopenPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    portraitImg = [self imageByScalingToMaxSize:portraitImg];
    // 裁剪
    HOTCHATClipViewController *clipView = [[HOTCHATClipViewController alloc] initWithImage:portraitImg];
    clipView.delegate = self;
    clipView.clipType = SQUARECLIP; //支持圆形:CIRCULARCLIP 方形裁剪:SQUARECLIP   默认:圆形裁剪
    clipView.radius = 150;   //设置 裁剪框的半径  默认120
    clipView.scaleRation = 3;//图片缩放的最大倍数
    clipView.isCamera = (picker.sourceType == UIImagePickerControllerSourceTypeCamera);
    [picker pushViewController:clipView animated:YES];
}
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < HOTCHATORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = HOTCHATORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (HOTCHATORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = HOTCHATORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (HOTCHATORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(HOTCHATClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage{
    dispatch_async(dispatch_get_main_queue(), ^{
        //        self.editEntity.head = editImage;
        //        self.headview.image = editImage;
        //        self.editEntity.avatar = nil;
        //        [self uploadAction];
        
        [self HOTCHATuploadActionImg:editImage];
        [clipViewController dismissViewControllerAnimated:YES completion:^{
            
        }];
    });
}

- (void)HOTCHATuploadActionImg:(UIImage *)img{
    [self HOTCHATstartLoading];
    __weak typeof (self) weakself = self;
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:[APPINFO defaultManager].accountid forKey:@"accountid"];
    [NetWorkTool HOTCHATUploadImageData:UPLOADHEADPIC_URL parameters:dic fileData:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *date = [self HOTCHATcompressQualityWithImd:img];
        [formData appendPartWithFileData:date name:@"uploadfile" fileName:@"headpic.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSString * _Nonnull HOTCHATmsgCode, NSDictionary * _Nonnull HOTCHATresultDic) {
        [self HOTCHATstopLoading];
        if ([HOTCHATresultDic[@"code"] integerValue] == 0) {
            weakself.HOTCHATheadView.HOTCHATheadImgView.image = img;
            weakself.HOTCHATheadView.HOTCHATheadImgView.contentMode = UIViewContentModeScaleAspectFill;
            
//            NSString *dataurl = [HOTCHATresultDic valueForKey:[HOTCHATStringUtils getThedataStr]];
//            self.model.headPic = dataurl;
//            if (dataurl.length > 0) {
//                NSString *HOTCHATfullURL = [dataurl HOTCHATfullURL].absoluteString;
//
//                EMSDImageCache *chches = [EMSDImageCache sharedImageCache];
//                [chches storeImage:img forKey:HOTCHATfullURL toDisk:YES];
//            }
            [NetWorkTool HOTCHATUpdateToken];
        }else{
            NSString *message = [HOTCHATresultDic valueForKey:@"message"];
            if (message.length > 0) {
                [self HOTCHATshowMessage:message];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull HOTCHATtask, NSError * _Nonnull error) {
        
    }];

    
}
- (NSData *)HOTCHATcompressQualityWithImd:(UIImage *)img {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(img, compression);
    if (data.length < HOTCHATMaxPhotoLength) return data;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 10; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(img, compression);
        if (data.length < HOTCHATMaxPhotoLength * 0.9) {
            min = compression;
        } else if (data.length > HOTCHATMaxPhotoLength) {
            max = compression;
        } else {
            break;
        }
    }
    return data;
}
- (void)HOTCHATsaveAction{
    _isSave = YES;
    if ([[APPINFO defaultManager] headPic].length == 0){
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow", nil)];
        return;
    }

    if ([APPINFO defaultManager].registerFlag == -2) {
        [self HOTCHATregisterActionIfIsSkip:NO];
    }else{
        [self HOTCHATstartLoading];
        __weak typeof (self)weakself = self;
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        APPINFO *appInfo = [APPINFO defaultManager];
        [dic setValue:appInfo.accountid forKey:@"accountid"];
        [dic setValue:self.model.nickName  forKey:@"nickName"];
        [dic setValue:self.model.age forKey:@"age"];
        
        [dic setValue:self.model.height forKey:@"height"];
        [dic setValue:self.model.minFeet forKey:@"minFeet"];
        [dic setValue:self.model.maxFeet forKey:@"maxFeet"];
        [dic setValue:self.model.weight forKey:@"weight"];
        
        [NetWorkTool HOTCHATRequestWithStringURL:UPDATEAccountINFO_URL progress:^(NSProgress * _Nonnull progress) {
            
        } RequestWay:@"POST" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
            [weakself HOTCHATstopLoading];
            if ([resultDictionary[@"code"] integerValue] == 0) {
                
                [NetWorkTool HOTCHATUpdateToken];
                [weakself HOTCHATenterApp];
            }
        } FailureBlock:^(NSError * _Nonnull error) {
            [weakself HOTCHATstopLoading];
        }];
  
    }
}
#pragma mark -- tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RegisterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RegisterCell"];
    if (cell == nil) {
        cell = [[RegisterCell alloc] initWithStyle:(UITableViewCellStyleValue1) reuseIdentifier:@"RegisterCell"];
    }
    cell.indexPath = indexPath;
    cell.model = self.model;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSInteger rowIndex = indexPath.row + 1;
    [self.view endEditing:YES];
    if (rowIndex == 0) {
        [self.HOTCHATselectView  HOTCHATcloseTheView];
    }else{
        [self.HOTCHATselectView setMsgType:rowIndex model:self.model];
        [self.HOTCHATselectView HOTCHATshowTheView:[UIApplication sharedApplication].keyWindow];
    }
}
- (void)HOTCHATselectedMsg:(NSString *)msg type:(MsgType)type num1:(NSInteger)num1 num2:(NSInteger)num2{
    
    switch (type) {
        case AgeMsg:
            self.model.age = msg;
            break;
        case HeightMsg:
            self.model.height = msg;
            self.model.minFeet = [NSString stringWithFormat:@"%ld",(long)num1];
            self.model.maxFeet = [NSString stringWithFormat:@"%ld",(long)num2];
            break;
        case WeightMsg:
            self.model.weight = msg;
            break;
        
            
        default:
            break;
    }
    [self.tableView reloadData];
}
- (void)clickSkip{
    //skipAction
    if ([[APPINFO defaultManager] accountid].length > 0 ) {
        //already login
        [self HOTCHATenterApp];
    }else{
        //need login
        [self HOTCHATregisterActionIfIsSkip:YES];
    }
    
}
- (void)HOTCHATenterApp{
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appdelegate initTabbarMenu];
}

- (void)HOTCHATregisterActionIfIsSkip:(BOOL)isSkip{
    [self HOTCHATstartLoading];
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[NSNumber numberWithInteger:self.sex] forKey:@"sex"];
    [dic setValue:@"1" forKey:@"clientType"];
    [dic setValue:[APPINFO defaultManager].appid forKey:@"appid"];
    [dic setValue:[APPINFO defaultManager].ver forKey:@"appVer"];
    [dic setValue:self.HOTCHATlongi forKey:@"muLongitud"];
    [dic setValue:self.HOTCHATlati forKey:@"muLatitude"];
    [dic setValue:[KeyChain getUUID] forKey:@"IMEI"];
    [NetWorkTool HOTCHATRequestWithStringURL:REGISTER_URL progress:^(NSProgress * _Nonnull progress) {
        
    } RequestWay:@"POST" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        [weakSelf HOTCHATstopLoading];
        NSInteger code = [resultDictionary[@"code"] integerValue];
        if (code == 0) {
            
            [UserInfoModel HOTCHATsaveUserInfoFromRegisterWithDic:resultDictionary Sex:self.sex];
            
            [weakSelf HOTCHATloginAction];
            
            if (isSkip) {
                
                [weakSelf HOTCHATenterApp];
            }else if (self ->_isSave){
                [self HOTCHATsaveAction];
            }
            
        }else if (code == 3002){
            //
        }
        
    } FailureBlock:^(NSError * _Nonnull error) {
        [weakSelf HOTCHATstopLoading];
    }];
}
- (void)HOTCHATloginAction{
    [self HOTCHATstartLoading];
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:[[APPINFO defaultManager] accountNumber] forKey:@"accountNumber"];
    [dic setValue:[[APPINFO defaultManager] accountPassword] forKey:@"password"];
    [NetWorkTool HOTCHATRequestWithStringURL:LOGIN_URL progress:^(NSProgress * _Nonnull progress) {
        
    } RequestWay:@"GET" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        [weakSelf HOTCHATstopLoading];
        if ([resultDictionary[@"code"] integerValue] == 0) {
            
            UserInfoModel *model = [UserInfoModel new];
            [model setValuesForKeysWithDictionary:resultDictionary[@"data"]];
            [model HOTCHATsaveTheUserInfo];
            weakSelf.model = model;
            weakSelf.HOTCHATheadView.HOTCHATtextField.text = self.model.nickName;
            [weakSelf.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
            
        }
        
    } FailureBlock:^(NSError * _Nonnull error) {
        [weakSelf HOTCHATstopLoading];
    }];
}
#pragma location
- (void)HOTCHATbegainLocation{
    
    self.HOTCHATLocation = [[CLLocationManager alloc]init];
    self.HOTCHATLocation.delegate = self;
    [self.HOTCHATLocation requestWhenInUseAuthorization];
    [self.HOTCHATLocation startUpdatingLocation];
    
}
// CLLocationManager delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    // 1.get userinfo
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    
    self.HOTCHATlongi = [NSNumber numberWithDouble:coordinate.longitude];
    self.HOTCHATlati = [NSNumber numberWithDouble:coordinate.latitude];
    
    // stop location
    [manager stopUpdatingLocation];
    
    [self HOTCHATregisterActionIfIsSkip:NO];
}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        //error
    }
    [self HOTCHATregisterActionIfIsSkip:NO];
}
@end
